package com.tbit.uqbike.tergateway.wa205pkg;

import com.tbit.uqbike.TerGatewayMain;
import com.tbit.uqbike.protocol.ATerPkg;
import com.tbit.uqbike.protocol.AnalyzeImpl.AProtocol;
import com.tbit.uqbike.protocol.AnalyzeImpl.WA205DeEnCoder;
import com.tbit.uqbike.service.db.DbService;
import com.tbit.uqbike.tergateway.data.TerGatewayData;
import com.tbit.uqbike.tergateway.entity.AConnInfo;
import com.tbit.uqbike.tergateway.entity.TerTempData;
import com.tbit.uqbike.tergateway.pojo.TerInfo;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * Created by MyWin on 2018/5/22 0022.
 */
public class Login extends ATerPkg {
    private static Logger logger = LoggerFactory.getLogger(ControlInfo.class);
    public String sn;
    public String lon;
    public String lat;
    public String safeStatus;
    public String batvol;
    public String func;
    public String rebootErr;


    @Override
    public void doBusiness() {
        logger.debug(this.toString());

        // 检查离线指令
        TerTempData terTempData = TerGatewayData.getTerTempDataByMno(this.mno);

        DbService dbService = TerGatewayMain.getDbService();
        TerInfo terExist = dbService.getTerInfoByMno(this.mno);
        if (terExist == null) {
            terExist = this.getTerInfo();
            dbService.insertTerInfo(terExist);
        } else {
            if (needUpdate(terExist)) {
                TerInfo newInfo = this.getTerInfo();
                terTempData.updateTerInfo(newInfo);
            }
        }

        if (terTempData.getOfflineOrderFlag()) {
            terTempData.checkOfflineOrder();
        }
    }

    private boolean needUpdate(TerInfo terExist) {
        if (this.mno.equals(terExist.getMachineNO())) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public boolean autoRsp() {
        return true;
    }

    @Override
    public ByteBuf getRsp(AConnInfo info, AProtocol protocol) {
        ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.directBuffer();
        WA205DeEnCoder.getCommRsp(byteBuf, "1");
        return byteBuf;
    }

    @Override
    public String toString() {
        return "CommPkg{" +
                ", sn='" + sn + '\'' +
                ", lon='" + lon + '\'' +
                ", lat='" + lat + '\'' +
                ", safeStatus='" + safeStatus + '\'' +
                ", batvol='" + batvol + '\'' +
                ", func='" + func + '\'' +
                ", rebootErr='" + rebootErr + '\'' +
                '}';
    }

    private TerInfo getTerInfo() {
        TerInfo info = new TerInfo();
        info.setFactoryCode("TBIT");
        info.setFunCode("");
        info.setImei("");
        info.setImsi("");
        info.setJoinTime(new Date());
        info.setMachineNO(this.mno);
        info.setSoftVersion("WA205");
        return info;
    }
}
